package com.hgx.su.example.common.springboot.mail.controller;

import cn.hutool.core.util.RandomUtil;
import com.hgx.su.example.common.springboot.mail.dto.SendEmailDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * Description:
 * author: HGX
 * DateTime: 2021-02-20 17:00
 */
@Controller
@RequestMapping("sendMail")
public class SendMailController {

    @Value("${spring.mail.username}")
    private String from;
    @Autowired
    private JavaMailSender mailSender;

    /**
     * 普通邮件发送
     */
    @PostMapping("commonEmail")
    @ResponseBody
    public Map<String, String> commonEmail(@RequestBody SendEmailDto toEmail) {
        //创建简单邮件消息
        SimpleMailMessage message = new SimpleMailMessage();
        //谁发的
        message.setFrom(from);
        //谁要接收
        message.setTo(toEmail.getTos());
        //邮件标题
        message.setSubject(toEmail.getSubject());
        //邮件内容
        message.setText(toEmail.getContent());

        Map<String, String> map = new HashMap<>();
        try {
            mailSender.send(message);
            map.put("status", "success");
        } catch (MailException e) {
            e.printStackTrace();
            map.put("status", "fail");
        }
        return map;

    }

    /**
     * HTML邮件发送
     */
    @PostMapping("htmlEmail")
    @ResponseBody
    public Map<String, String> htmlEmail(@RequestBody SendEmailDto toEmail) throws MessagingException {
        //创建一个MINE消息
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper minehelper = new MimeMessageHelper(message, true);
        //谁发
        minehelper.setFrom(from);
        //谁要接收
        String tos = toEmail.getTos();
        String[] split = tos.split(",");
        minehelper.setTo(split);
        //邮件主题
        minehelper.setSubject(toEmail.getSubject());
        //邮件内容   true 表示带有附件或html
        minehelper.setText(toEmail.getContent(), true);

        Map<String, String> map = new HashMap<>();
        try {
            mailSender.send(message);
            map.put("content", toEmail.getTos() + "=========" + toEmail.getContent());
            map.put("status", "HTML邮件成功");
        } catch (MailException e) {
            e.printStackTrace();
            map.put("status", "HTML邮件失败");
        }

        return map;
    }

    /**
     * 含静态资源邮件发送
     */
    @PostMapping("staticEmail")
    @ResponseBody
    public Map<String, String> staticEmail(SendEmailDto toEmail, @RequestParam("files") MultipartFile[] multipartFiles, String resIds) {
        //创建一个MINE消息
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            //谁发
            helper.setFrom(from);
            //谁接收
            String tos = toEmail.getTos();
            String[] split = tos.split(",");
            helper.setTo(split);
            //邮件主题
            helper.setSubject(toEmail.getSubject());
            //邮件内容   true 表示带有附件或html
            //邮件内容拼接
            String content = "<html><body>";
            //蒋 multpartfile 转为file
            String[] split1 = resIds.split(",");

            StringBuilder builder = new StringBuilder() ;
            for (int i = 0; i < multipartFiles.length; i++) {
                builder.append("<img width='250px' src='cid:"+split1[i]+"'>") ;
            }

            content = content+ builder.toString()+ toEmail.getContent() + "</body></html>" ;
            helper.setText(content, true);

            for (int i = 0; i < multipartFiles.length; i++) {
                File multipartFileToFile = MultipartFileToFile(multipartFiles[i]);
                FileSystemResource res = new FileSystemResource(multipartFileToFile);
                //添加内联资源，一个id对应一个资源，最终通过id来找到该资源
                helper.addInline(split1[i], res);
            }

            mailSender.send(message);

            Map<String, String> map = new HashMap<>();
            map.put("content", toEmail.getTos() + "=========" + toEmail.getContent());
            map.put("status", "嵌入静态资源的邮件已经发送");
            return map;
        } catch (MessagingException e) {
            Map<String, String> map = new HashMap<>();
            map.put("status", "嵌入静态资源的邮件发送失败");
            return map;
        }
    }

    private File MultipartFileToFile(MultipartFile multiFile) {
        // 获取文件名
        String fileName = RandomUtil.randomNumbers(6)+ multiFile.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 若需要防止生成的临时文件重复,可以在文件名后添加随机码

        try {
            File file = File.createTempFile(fileName, prefix);
            multiFile.transferTo(file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 带附件邮件发送
     */
    @PostMapping("enclosureEmail")
    @ResponseBody
    public Map<String, String> enclosureEmail(SendEmailDto toEmail, @RequestParam("file") MultipartFile multipartFile) {
        //创建一个MINE消息
        MimeMessage message = mailSender.createMimeMessage();
        Map<String, String> map = new HashMap<>();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            //谁发
            helper.setFrom(from);
            //谁接收
            String tos = toEmail.getTos();
            String[] split = tos.split(",");
            helper.setTo(split);
            //邮件主题
            helper.setSubject(toEmail.getSubject());
            //邮件内容   true 表示带有附件或html
            helper.setText(toEmail.getContent(), true);
            File multipartFileToFile = MultipartFileToFile(multipartFile);
            FileSystemResource file = new FileSystemResource(multipartFileToFile);
            String filename = file.getFilename();
            //添加附件
            helper.addAttachment(filename, file);
            mailSender.send(message);
            map.put("content", toEmail.getTos() + "=========" + toEmail.getContent());
            map.put("status", "附件邮件已经发送");
        } catch (MessagingException e) {
            e.printStackTrace();
            map.put("status", "附件邮件发送失败");
        }
        return map;
    }
}
